<template>
  <div class="matrix-background">
    <canvas ref="canvasRef"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'

const props = defineProps({
  config: {
    type: Object,
    default: () => ({
      color: '#00ff00',
      speed: 'medium',
      density: 'high'
    })
  }
})

const canvasRef = ref(null)
let ctx = null
let columns = []
let animationId = null

const init = () => {
  const canvas = canvasRef.value
  if (!canvas) return

  canvas.width = canvas.offsetWidth
  canvas.height = canvas.offsetHeight
  ctx = canvas.getContext('2d')

  const fontSize = 14
  const columnCount = Math.floor(canvas.width / fontSize)
  
  columns = []
  for (let i = 0; i < columnCount; i++) {
    columns[i] = 0
  }
}

const getColor = () => {
  if (props.config.color === 'rainbow') {
    const colors = ['#ff0000', '#ff7f00', '#ffff00', '#00ff00', '#0000ff', '#4b0082', '#9400d3']
    return colors[Math.floor(Math.random() * colors.length)]
  }
  return props.config.color
}

const getSpeed = () => {
  const speedMap = {
    slow: 0.02,
    medium: 0.04,
    fast: 0.06
  }
  return speedMap[props.config.speed] || 0.04
}

const getDensity = () => {
  const densityMap = {
    low: 0.98,
    medium: 0.96,
    high: 0.94
  }
  return densityMap[props.config.density] || 0.96
}

const animate = () => {
  if (!ctx || !canvasRef.value) return

  // 半透明黑色覆盖，产生拖尾效果
  ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'
  ctx.fillRect(0, 0, canvasRef.value.width, canvasRef.value.height)

  const fontSize = 14
  const speed = getSpeed()
  const density = getDensity()

  ctx.font = `${fontSize}px monospace`

  columns.forEach((y, index) => {
    // 随机字符（数字、字母、日文片假名）
    const chars = 'ｱｲｳｴｵｶｷｸｹｺｻｼｽｾｿﾀﾁﾂﾃﾄﾅﾆﾇﾈﾉﾊﾋﾌﾍﾎﾏﾐﾑﾒﾓﾔﾕﾖﾗﾘﾙﾚﾛﾜﾝ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    const text = chars.charAt(Math.floor(Math.random() * chars.length))

    // 渐变色（头部亮，尾部暗）
    const brightness = Math.floor(255 * (1 - y / canvasRef.value.height))
    
    if (props.config.color === 'rainbow') {
      ctx.fillStyle = getColor()
    } else {
      ctx.fillStyle = props.config.color
    }

    ctx.fillText(text, index * fontSize, y)

    // 随机重置列
    if (y > canvasRef.value.height && Math.random() > density) {
      columns[index] = 0
    }

    // 移动列
    columns[index] += fontSize * speed * 60
  })

  animationId = requestAnimationFrame(animate)
}

const handleResize = () => {
  init()
}

onMounted(() => {
  init()
  animate()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (animationId) {
    cancelAnimationFrame(animationId)
  }
  window.removeEventListener('resize', handleResize)
})

watch(() => props.config, () => {
  init()
}, { deep: true })
</script>

<style scoped>
.matrix-background {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: #000000;
}

canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
}
</style>

